package com.atguigu.spzx.common.log.aspect;

import com.atguigu.spzx.common.log.annotation.Log;
import com.atguigu.spzx.common.log.service.ISysLogService;
import com.atguigu.spzx.common.log.utils.LogUtil;
import com.atguigu.spzx.exception.BaseException;
import com.atguigu.spzx.model.vo.common.entity.system.SysOperLog;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Component
@Aspect
@RequiredArgsConstructor
public class OperationLogAspect {

     private final ISysLogService sysLogService;
     //环绕通知
    @Around("@annotation(sysLog)")
    public Object doAroundAdvice(ProceedingJoinPoint joinPoint, Log sysLog){
        //1.封装日志模型
        SysOperLog sysOperLog = new SysOperLog();
        LogUtil.beforeHandleLog(sysLog,joinPoint,sysOperLog);
        Object proceed=null;
        try {
            proceed=joinPoint.proceed();
            LogUtil.afterHandlLog(sysLog,proceed,sysOperLog,0,null);
        } catch (Throwable e) {
            LogUtil.afterHandlLog(sysLog,proceed,sysOperLog,1,e.getMessage());
            //产生异常要将异常抛出,否则事务会失效
            throw new BaseException("日志切面记录异常");
        }
        //调用方方法将日志加到数据库中
        sysLogService.saveOperationLog(sysOperLog);
        return proceed;
    }

}
